//
//  OMTAlbum.m
//  OMTImagePicker
//
//  Created by yizhaorong on 2017/11/15.
//

#import "OMTAlbum.h"
#import "OMTAlbumManager.h"
#import <Photos/Photos.h>

// 相册加载完成
NSString *const OMTAlbumAssetsLoadedNotification = @"OMTAlbumAssetsLoadedNotification";

@implementation OMTAlbum

- (void)setResult:(id)result {
    _result = result;
    if (self.albumManager.builder.showVedio) {
        self.count = [(PHFetchResult *)result count];
    } else {
        self.count = [(PHFetchResult *)result countOfAssetsWithMediaType:PHAssetMediaTypeImage];
    }
    __weak typeof(self) weakSelf = self;
    [self.albumManager assetsFromFetchResult:result completion:^(NSArray<OMTAsset *> *assets, BOOL finished) {
        typeof(weakSelf) strongSelf = weakSelf;
        if (!strongSelf) return;
        
        if (!finished) return;
        strongSelf.assets = assets;
        strongSelf.count = assets.count;
        [strongSelf checkSelectedAssets];
        [[NSNotificationCenter defaultCenter] postNotificationName:OMTAlbumAssetsLoadedNotification object:strongSelf];
    }];
}

- (void)checkSelectedAssets {
    self.selectedCount = 0;
    NSMutableArray *selectedAssets = [NSMutableArray array];
    for (OMTAsset *asset in self.selectedAssets) {
        [selectedAssets addObject:asset.asset];
    }
    for (OMTAsset *asset in self.assets) {
        if ([selectedAssets containsObject:asset.asset]) {
            self.selectedCount ++;
        }
    }
}

- (BOOL)isEqual:(id)object {
    if ([object isKindOfClass:self.class]) {
        OMTAlbum *album = (OMTAlbum *)object;
        return [album.name isEqualToString:self.name];
    }
    return NO;
}

@end
